/**
 * @description router全局配置，如有必要可分文件抽离，其中asyncRoutes只有在intelligence模式下才会用到，pro版只支持remixIcon图标，具体配置请查看vip群文档
 */
import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory, createWebHistory, RouteRecordName } from 'vue-router'
import { authentication, base, isHashRouterMode } from '/@lib/config'
import { setupRouterGuard } from '/@/router/guard'

import { asyncRoutes } from '/@/router/routes/routes.static.ts'
import { constantRoutes } from '/@/router/routes/routes.inner.ts'

export { constantRoutes, asyncRoutes }

const router = createRouter({
  history: isHashRouterMode ? createWebHashHistory(base) : createWebHistory(base),
  routes: constantRoutes as RouteRecordRaw[]
})

const fatteningRoutes = (routes: AppRouteRecordRaw[]): AppRouteRecordRaw[] => {
  return routes.flatMap((route) => {
    return route.children ? fatteningRoutes(route.children) : route
  })
}

const addRouter = (routes: AppRouteRecordRaw[]) => {
  routes.forEach((route: AppRouteRecordRaw) => {
    if (!router.hasRoute(route.name)) router.addRoute(route as RouteRecordRaw)
    if (route.children) addRouter(route.children)
  })
}

export const resetRouter = (routes: AppRouteRecordRaw[] = constantRoutes) => {
  routes.map((route: AppRouteRecordRaw) => {
    if (route.children) route.children = fatteningRoutes(route.children)
  })
  router.getRoutes().forEach((route) => {
    if (route.name) {
      const routeName: RouteRecordName = route.name
      router.hasRoute(routeName) && router.removeRoute(routeName)
    }
  })
  addRouter(routes)
}

export const setupRouter = (app: App<Element>) => {
  if (authentication === 'intelligence') addRouter(asyncRoutes)
  // setupPermissions(router);
  setupRouterGuard(router)
  app.use(router)
  return router
}

export default router
